package mo.leetcode_top;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class L15 {

    public List<List<Integer>> threeSum(int[] nums) {
        if (nums.length < 3) {
            return new ArrayList<>();
        }
        Arrays.sort(nums);
        List<List<Integer>> res = new ArrayList<>();
        int len = nums.length;
        for (int i = 0; i < len - 2; i++) {
            if (nums[i] > 0) {
                break;
            }
            if ((i > 0 && nums[i] == nums[i-1])) {
                continue;
            }
            int target = 0 - nums[i];
            int j = i + 1;
            int k = len - 1;
            while (j < k) {
                if (nums[j] + nums[k] == target) {
                    res.add(Arrays.asList(nums[i], nums[j], nums[k]));
                    while (j < k && nums[j] == nums[j+1]) {
                        j++;
                    }
                    while (j < k && nums[k] == nums[k-1]) {
                        k--;
                    }
                    j++;
                    k--;
                } else if (nums[j] + nums[k] < target) {
                    j++;
                } else {
                    k--;
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        L15 test = new L15();
        System.out.println(test.threeSum(new int[]{-2,0,1,1,2}));
    }
}
